package com.video.information.ui.information

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.video.information.R
import com.video.information.data.model.Information
import com.video.information.ui.common.ui.BaseFragment
import kotlinx.android.synthetic.main.fragment_information.recyclerView
import kotlinx.android.synthetic.main.fragment_information.smartRefreshLayout

class InformationFragment : BaseFragment() {

    private var linearLayoutManager: LinearLayoutManager? = null

    private var informationAdapter: InformationAdapter? = null

    private var informationData: List<Information.RECORDSBean>? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return onCreateView(inflater.inflate(R.layout.fragment_information, container, false))
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        linearLayoutManager = LinearLayoutManager(requireContext())
        linearLayoutManager?.orientation = LinearLayoutManager.VERTICAL
        recyclerView.layoutManager = linearLayoutManager
        informationAdapter = InformationAdapter()
        recyclerView.adapter = informationAdapter
        smartRefreshLayout.setOnRefreshListener {
            notifyInformationData(true)
        }
        smartRefreshLayout.setOnLoadMoreListener {
            notifyInformationData(false)
        }
        notifyInformationData(true)
    }

    /**
     * 更新或刷新recyclerView
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun notifyInformationData(isRefresh: Boolean) {
        if (isRefresh) {
            smartRefreshLayout.finishRefresh(true)
        } else {
            smartRefreshLayout.finishLoadMore(true)
            return
        }
        informationData = Gson().fromJson(Information.mInformation, Information::class.java).RECORDS
        informationAdapter?.informationData = informationData
        informationAdapter?.notifyDataSetChanged()
    }

    companion object {
        fun newInstance() = InformationFragment()
    }
}